package com.zzx.test.thread.juc;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zzx
 * 普通线程与虚拟线程的运行效率对比
 * @since 2025/10/20 14:39
 */
@Slf4j
public class VirtualThreadTest1 {

    int threadNum = 100;
    int taskNum = 1000;

    @Test
    public void threadTest() {
        long start = System.currentTimeMillis();
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        for (int i = 0; i < taskNum; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executor.close();
        System.out.println("finish: " + (System.currentTimeMillis() - start));
        executor.shutdown();
    }

    @Test
    public void virtualThreadTest() {
        long start = System.currentTimeMillis();
        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
        for (int i = 0; i < taskNum; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executor.close();
        System.out.println("finish: " + (System.currentTimeMillis() - start));
        executor.shutdown();
    }

}
